package y23.Nov;

import java.io.*;
import java.util.Scanner;

public class Test6 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的路径: ");
        String path = scanner.next();
        File rootPath = new File(path);
        if (!rootPath.isDirectory()) {
            System.out.println("没有该路径");
            return;
        }
        System.out.println("请输入要查找文件中名称或内容的关键词: ");
        String word = scanner.next();
        System.out.println("检测到符合条件的文件：");
        scanDir(rootPath, word);
    }
    private static void scanDir(File rootPath, String word) {
        File[] files = rootPath.listFiles();
        if (files == null) {
            return;
        }
        for (File f : files) {
            if (f.isFile()) {
                checkFile(f,word);
            } else {
                scanDir(f, word);
            }
        }
    }

    private static void checkFile(File file,String word){
        if (file.getName().contains(word)) {
            System.out.println(file.getAbsolutePath());
        }else{
            try(Reader reader = new FileReader(file)){
                StringBuffer str = new StringBuffer();
                while (true){
                    char[] cubf = new char[1024];
                    int n = reader.read(cubf);
                    if (n == -1){
                        break;
                    }
                    for (int i = 0;i < n;i++){
                        str.append(cubf[i]);
                    }
                }
                if(str.toString().contains(word)){
                    System.out.println(file.getAbsolutePath());
                }
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
